package main

import (
	"flag"
	"fmt"
	"os"
	"runtime/pprof"
	"time"
)

func problematicFunc() {
	var c chan int
	for {
		select {
		case v := <-c:
			fmt.Printf("receive from cahn, value: %v\n", v)
		default:
		}
	}
}

func main() {
	var isCPUPprof bool // 开启 CPU profile 标志位
	var isMemPprof bool // 开启 内存 profile 标志位

	flag.BoolVar(&isCPUPprof, "cpu", false, "turn cpu pprof on")
	flag.BoolVar(&isMemPprof, "mem", false, "turn mem pprof on")
	flag.Parse()
	if isCPUPprof {
		f1, err := os.Create("./cpu.pprof") // 显示cpu调用信息
		if err != nil {
			fmt.Println("create cpu pprof failed, err:", err)
			return
		}
		pprof.StartCPUProfile(f1)
		defer func() {
			pprof.StopCPUProfile()
			f1.Close()
		}()
	}
	for i := 0; i < 3; i++ {
		go problematicFunc()
	}
	time.Sleep(10 * time.Second)

	if isMemPprof {
		f2, err := os.Create("./mem.pprof") // 显示内存使用信息
		if err != nil {
			fmt.Println("create mem pprof failed, err:", err)
			return
		}
		pprof.WriteHeapProfile(f2)
		defer func() {
			f2.Close()
		}()
	}
}
